package com.cross.excel;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import jxl.Cell;
import jxl.Range;
import jxl.Workbook;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

import com.cross.core.AbstractReader;
import com.cross.core.Column;
import com.cross.core.Header;
import com.cross.core.Item;
import com.cross.core.Row;
import com.cross.exception.FileValidatorException;
import com.cross.util.ItemType;
import com.cross.util.StringUtils;

/**
 * excel读取器实现类
 *
 * 2009-2-5
 * @author craziness_stone
 */
@SuppressWarnings("unchecked")
public class SimpleExcelReader extends AbstractReader {

	// excel对象
	private WritableWorkbook book = null;
	// 当前Sheet
	private WritableSheet sheet = null;
	// 当前Sheet号
	private int sheetIndex = 0;
	// book中sheet数量
	private int bookSize = 0;
	// 当前工作表的行数
	private int rowNum = 0;
	//当前工作表中的所有合并的单元格
	private Range[] mergedCells;
	
	private File temp;
	
	public SimpleExcelReader(String file) throws Exception{
		if (StringUtils.isEmpty(file)) {
			throw new FileValidatorException("文件不存在.");
		}
		File temp = new File(file);
		if(temp==null || !temp.exists() || !temp.isFile()){
			throw new FileValidatorException("文件不存在.");
		}
		init(temp);
	}
	public SimpleExcelReader(File file) throws Exception{
		if (null == file) {
			throw new FileValidatorException("文件不存在.");
		}
		init(file);
	}
	/**
	 * 初始化
	 * 
	 * 2009-2-5
	 * @author craziness_stone
	 * @param file
	 * @throws Exception
	 */
	private void init(File file) throws Exception {
		book = getWorkbook(file);
		bookSize = book.getNumberOfSheets();
		if (book == null || bookSize < 1) {
			throw new FileValidatorException("文件中没有任何工作薄");
		}
		header = this.getHeader(book.getSheet(0));
	}
	/**
	 * 获得工作表
	 * 
	 * 2008-12-19
	 * 
	 * @author craziness_stone
	 * @param file
	 * @return
	 */
	private WritableWorkbook getWorkbook(File file) throws Exception {
		try {
			// 打开Excel模板
			Workbook template = Workbook.getWorkbook(file);
			// 装载模板
			synchronized (this) {
				temp = new File("cross_" + System.currentTimeMillis()
						+ ".xls");
			}
			temp.createNewFile();
			return Workbook.createWorkbook(temp, template);
			
		} catch (Exception e) {
			throw new FileValidatorException("无法解析上传文件.");
		}
	}
	
	protected boolean nextRow(){
		if (_nextRow()) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 下一行
	 * 
	 * 2009-1-19
	 * 
	 * @author craziness_stone
	 * @return
	 */
	private boolean _nextRow() {

		currentRow = toRow(sheet.getRow((int)rowIndex));
		currentRow.setNumber(totalIndex++);
		if (currentRow.empty()) {
			return _nextRow();
		}
		return true;
	}
	
	private void moveNext(){
		if (++rowIndex >= rowNum) {
			_nextSheet();
		}
	}
	
	private Cell[] getRow(){
		
		if(mergedCells==null || mergedCells.length<1){
			return sheet.getRow((int)rowIndex);
		}
		Cell cell = null;
		Cell temp = null;
		for(Range r : mergedCells){
			temp = r.getTopLeft();
			if(temp.getRow()==(int)rowIndex){
				if(cell==null){
					cell = temp;
				}
				if(cell.getColumn()>temp.getColumn()){
					cell = temp;
				}
			}
		}
		
		Row row = null;
		if(isParentRow()){
			row.setSubRows(getSubRow());
		}
		
		return null;
	}
	
	private List<Row> getSubRow(){
		List<Row> subRows = new ArrayList<Row>(0);
		for(Row r : subRows){
			
		}
		
		return null;
	}
	
	
	private boolean isParentRow(){
		return false;
	}

	private Row toRow(Cell[] cells){
		Row r = new Row();
		int i = 0;
		Item item = null;
		for(Cell e : cells){
			item = toItem(e);
			item.setColumn(i++);
			r.append(item);
		}
		return r;
	}
	
	private Item toItem(Cell c){
		//TODO 增加对不同excel数据类型转换不同的ItemType的支持
		return new Item<String>(c.getContents(),ItemType.TYPE_STRING);
	}
	/**
	 * 下一个工作表
	 * 
	 * 2009-1-17
	 * 
	 * @author craziness_stone
	 * @return
	 */
	private boolean _nextSheet() {
		if (sheetIndex >= bookSize) {
			return false;
		}
		sheet = book.getSheet(sheetIndex++);
		this.mergedCells = sheet.getMergedCells();
		try {
			header = getHeader(sheet);
		} catch (Exception e) {
			return _nextSheet();
		}
		rowNum = sheet.getRows();
		rowIndex = 0;
		return true;
	}
	
	private Header getHeader(WritableSheet sheet) throws FileValidatorException{
		if(1>sheet.getRows()){
			throw new FileValidatorException("没有任何数据");
		}
		Header header = new Header();
		Cell[] cells = sheet.getRow(0);
		int temp =0 ;
		for(Cell c : cells){
			header.add(new Column(temp++,c.getContents(),"java.lang.String"));
		}
		return header;
	}


	/**
	 * 关闭工作表
	 * 
	 * 2009-1-20
	 * 
	 * @author craziness_stone 
	 */
	@Override
	public void close() {
		try {
			book.write();
			book.close();
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			temp.delete();
		}
	}
}